package dao

import (
	"time"

	"gitee.com/krio/grpc-common/conf"
	"gitee.com/krio/grpc-common/model"
	"gitee.com/krio/helper/logger"

	_ "github.com/go-sql-driver/mysql"
	"github.com/xormplus/core"
	"github.com/xormplus/xorm"
)

var (
	x   *xorm.Engine
	err error
)

func InitDao() *xorm.Engine {
	url := conf.C.Mysql.URL
	fPath := conf.C.Mysql.FPath
	x, err = xorm.NewEngine("mysql", url)
	if err != nil {
		logger.Fatalf("mysql connect failed, err:", err)
	}
	maxIdle := conf.C.Mysql.MaxIdle
	x.SetConnMaxLifetime(2 * time.Hour)
	x.SetMaxOpenConns(200)
	x.SetMaxIdleConns(maxIdle)
	x.SetTableMapper(core.NewPrefixMapper(core.GonicMapper{}, ""))
	x.SetColumnMapper(core.GonicMapper{})
	// 注册sql模板文件
	err = x.RegisterSqlTemplate(xorm.Pongo2(fPath+"/stpl", ".stpl"))
	if err != nil {
		logger.Fatalf("register sql template failed, err:", err)
	}

	if err = x.Ping(); err != nil {
		logger.Fatalf("mysql ping failed, err:", err)
	}
	// 自动注册表
	err = x.Sync2(
		model.Region{},
	)
	if err != nil {
		logger.Fatalf("mysql sync failed, err:", err)
	}
	x.ShowSQL(conf.C.Mysql.ShowSQL)

	return x
}
